package com.lihao.jetpackcore.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.lihao.jetpackcore.ext.getVmClazz
import com.lihao.jetpackcore.network.manager.NetState
import com.lihao.jetpackcore.network.manager.NetworkStateManager

/**
 * Created by lihao on 2020/5/14.
 * Describe: .
 */
abstract class BaseVmFragment<VM : BaseViewModel> : Fragment() {

    private var isFirst: Boolean = true

    lateinit var mViewModel: VM

    abstract fun layoutId(): Int

    abstract fun initView(savedInstanceState: Bundle?)

    abstract fun createObserver()

    /**
     * 懒加载
     */
    abstract fun lazyLoadData()

    abstract fun showLoading(message: String = "请求网络中...")

    abstract fun dismissLoading()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(layoutId(), container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mViewModel = createViewModel()
        initView(savedInstanceState)
        onVisible()
        registerUiChange()
        NetworkStateManager.instance.mNetworkStateCallback.observe(this, Observer {
            onNetworkStateChanged(it)
        })
    }

    override fun onResume() {
        super.onResume()
        onVisible()
    }

    private fun onVisible(){
        if(lifecycle.currentState == Lifecycle.State.STARTED && isFirst){
            lazyLoadData()
            isFirst = false
            createObserver()
        }
    }

    /**
     * 网络变化监听 子类重写
     */
    open fun onNetworkStateChanged(netState: NetState) { }

    private fun createViewModel(): VM {
        return ViewModelProvider(
            this,
            ViewModelProvider.AndroidViewModelFactory(this.requireActivity().application)
        ).get(getVmClazz(this))
    }

    /**
     * 注册Loading事件
     */
    private fun registerUiChange() {
        mViewModel.loadingChange.showDialog.observe(this, Observer {
            showLoading()
        })
        mViewModel.loadingChange.dismissDialog.observe(this, Observer {
            dismissLoading()
        })
    }
}